<template>
  <div class="absolute z-0 flex-1 w-full h-full bg-gray-100 overflow-hidden">
    <!-- 主Canvas画布 - 纯渲染层，不包含业务逻辑 -->
    <canvas
      ref="canvasRef"
      class="absolute inset-0 w-full h-full cursor-crosshair"
      @mousedown="interactionService.handleMouseDown"
      @mousemove="interactionService.handleMouseMove"
      @mouseup="interactionService.handleMouseUp"
      @wheel="interactionService.handleWheel"
      @contextmenu="interactionService.handleContextMenu"
      
    ></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useCanvas } from '@/composables/design/useCanvas'
import { useRender } from '@/composables/design/useRender'
import { useInteraction } from '@/composables/design/useInteraction'
import { useCanvasStore } from '@/stores'

// ==================== 组件职责说明 ====================
// MainCanvas组件职责：
// 1. 纯渲染层：负责Canvas的渲染和基础交互
// 2. 事件转发：将用户交互事件转发给应用层处理
// 3. 视图管理：管理Canvas尺寸和基础视图状态
// 4. 不包含业务逻辑：所有业务逻辑都在领域服务中

// ==================== 服务依赖注入 ====================
// Canvas Store
const canvasStore = useCanvasStore()

// 领域层：Canvas业务逻辑服务
const canvasService = useCanvas()

// 渲染层：Canvas渲染服务
const renderService = useRender(
  canvasService.ctx,
  canvasService.viewport,
  canvasService.layers,
  canvasService.selectedObjects,
  canvasService.hoveredObject,
  canvasService.canvasSettings
)

// 交互层：用户交互服务
const interactionService = useInteraction(canvasService)

// ==================== 组件内部状态 ====================
// Canvas引用
const canvasRef = ref(null)

// ==================== Canvas 生命周期管理 ====================
/**
 * Canvas初始化
 * 职责：设置Canvas尺寸、启动渲染循环
 */
const initCanvas = () => {
  const canvas = canvasRef.value
  if (!canvas) return
  
  // 将canvas元素存储到store中
  canvasStore.setCanvasElement(canvas)
  
  // 初始化Canvas服务
  canvasService.initializeCanvas(canvas)
  
  // 启动渲染循环
  startRenderLoop()
}

/**
 * 渲染循环
 * 职责：持续渲染Canvas内容
 */
let animationId = null
const startRenderLoop = () => {
  const render = () => {
    if (canvasService.ctx.value) {
      // 委托给渲染服务进行渲染
      renderService.render(
        canvasService.selectionBox,
        interactionService.mousePosition
      )
    }
    
    animationId = requestAnimationFrame(render)
  }
  
  render()
}

// ==================== 组件生命周期 ====================
onMounted(() => {
  initCanvas()
})

onUnmounted(() => {
  if (animationId) {
    cancelAnimationFrame(animationId)
  }
  // 清理Canvas资源
  canvasService.cleanupCanvas()
})
</script>

<style scoped>
/* Canvas样式 */
</style>
